package com.smartcat.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.smartcat.dao.GroupInfoMapper;
import com.smartcat.dao.UserGroupMapMapper;
import com.smartcat.model.GroupInfo;
import com.smartcat.model.GroupInfoExample;
import com.smartcat.model.UserGroupMap;
import com.smartcat.service.GroupService;

@Service("groupService")
public class GroupServiceImpl implements GroupService {

	private GroupInfoMapper groupInfoMapper;
	
	private UserGroupMapMapper userGroupMapMapper;
	
	@Autowired
	public void setGroupInfoMapper(GroupInfoMapper groupInfoMapper){
		this.groupInfoMapper = groupInfoMapper;
	}
	
	
	public void setUserGroupMapMapper(UserGroupMapMapper userGroupMapMapper) {
		this.userGroupMapMapper = userGroupMapMapper;
	}

	@Override
	public void createGroupInfo(GroupInfo groupInfo) {
		// TODO Auto-generated method stub
		groupInfoMapper.insert(groupInfo);
	}

	@Override
	public GroupInfo getGroupInfo(String groupName) {
		// TODO Auto-generated method stub
		System.out.println("getGroupInfo() start ...");
		GroupInfoExample example = new GroupInfoExample();
		example.or().andGroupNameEqualTo(groupName);
		List<GroupInfo> groupInfoList = groupInfoMapper.selectByExample(example);
		if(groupInfoList != null && groupInfoList.size() == 1 ){
			return groupInfoList.get(0);
		}
		return null;
	}

	@Override
	public List<GroupInfo> getAllGroupInfo() {
		// TODO Auto-generated method stub
		System.out.println("getAllGroupInfo start ...");
		GroupInfoExample example = new GroupInfoExample();
		List<GroupInfo> allGroupInfo = groupInfoMapper.selectByExample(example);
		return allGroupInfo;
	}
	
	@Override
	public void updateGroupInfo(GroupInfo groupInfo){
		System.out.println("updateGroupInfo start ...");
//		GroupInfoExample example = new GroupInfoExample();
		groupInfoMapper.updateByPrimaryKeySelective(groupInfo);
	}

	@Override
	public void deleteGroupById(Integer groupId) {
		//this.groupInfoMapper.deleteByPrimaryKey(groupId);
		GroupInfo record=new GroupInfo();
		record.setGroupId(groupId);
		record.setGroupName("deleted");
		this.groupInfoMapper.updateByPrimaryKeySelective(record);
	}

	
	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
	public void createGroupInfoWithMembers(GroupInfo groupInfo, List<UserGroupMap> users) {
		if(groupInfo==null){
			return;
		}
		this.groupInfoMapper.insert(groupInfo);
		//System.out.println();
		if(users!=null && users.size()>0){
			for(UserGroupMap record:users){
				record.setGroupId(groupInfo.getGroupId());
				this.userGroupMapMapper.insert(record);
			}
		}
		
	}
	
	

}
